<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\NewsReadLog;
use app\common\model\UserNotify;
use app\common\tool\Result;
use think\Response;
use app\common\model\News as NewsModel;

class News extends Base
{
    public function index(): Response
    {
        $param = $this->request->param();
        $map['is_del'] = 0;
        $map['status'] = 1;
        if (isset($param['type']) && $param['type']) {
            $map['type'] = $param['type'];
        }
        if (isset($param['position']) && $param['position']) {
            $map['position'] = $param['position'];
        }
        $list = NewsModel::getPageList($map, 'id,title,describe,images,create_time', $this->getPage(), $this->getLimit());
        foreach ($list['data'] as &$item){
            $item->is_read = $this->user && NewsReadLog::where(['news_id'=>$item->id, 'uid'=>$this->user->id])->count() ? 1 : 0;
            $this->user && $this->read($item, $this->user);
        }
        return Result::fastReturn($list);
    }

    public function info(): Response
    {
        $id = $this->request->param('id');
        $info = NewsModel::where('id', $id)->where('status', 1)->where('is_del', 0)->field('id,title,describe,images,content,create_time,status,is_del')->find();
        if (empty($info)) {
            return Result::fail('记录不存在');
        }
        unset($info->status);
        unset($info->is_del);
        $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
        $info->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content));
        $info->content = str_replace('\\', '', $info->content);

        $this->read($info, $this->user);
        return Result::success('success', $info);
    }

    /**
     * 未读数量
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function notReadNum(): Response
    {
        $new_ids = NewsModel::where(['is_del'=>0,'position'=>1,'status'=>1])->column('id');
        $total = count($new_ids);
        $read_count = $this->user ? NewsReadLog::whereIn('news_id', $new_ids)->where('uid', $this->user->id)->count() : 0;

        $notifyCount = $this->user ? UserNotify::where('uid', $this->user->id)->where('is_read', 0)->count() : 0;

        $not_read_num = $total - $read_count + $notifyCount;

        return Result::success('success', ['not_read_num'=>$not_read_num]);
    }

    private function read($news, $user): bool
    {
        if($user){
            $param = [
                'uid' => $user->id,
                'news_id' => $news->id
            ];
            if(!NewsReadLog::where($param)->find()){
                NewsReadLog::create($param);
            }
        }
        return true;
    }
}

